package edu.whut.framework.aop.interceptor;

import edu.whut.framework.aop.service.OrderAspectService;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.List;

/**
 * @program: MySpring
 * @description: 自定义拦截器
 * @author: Wayne
 * @create: 2020-08-07 10:10
 **/
public class MyMethodInterceptor implements MethodInterceptor {
    private Class<?> targetClass;
    private List<OrderAspectService> aspectServiceList;

    public MyMethodInterceptor(Class<?> targetClass, List<OrderAspectService> aspectServiceList) {
        this.targetClass = targetClass;
        this.aspectServiceList = sortAspectService(aspectServiceList);
    }

    private List<OrderAspectService> sortAspectService(List<OrderAspectService> aspectServiceList) {
        aspectServiceList.sort(Comparator.comparingInt(OrderAspectService::getOrder));
        return aspectServiceList;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Object result = null;
        invokeBeforeAspect(o, method, objects, methodProxy);
        result = methodProxy.invokeSuper(o, objects);
        return result;
    }

    private void invokeBeforeAspect(Object o, Method method, Object[] objects, MethodProxy methodProxy) {
        for(OrderAspectService aspectService : aspectServiceList) {
            aspectService.getAspectService().before(o, method, objects, methodProxy);
        }
    }
}
